package com.example.work;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.nfc.Tag;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.widget.ImageView;
import android.widget.TextView;


import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.drawable.RoundedBitmapDrawable;
import androidx.core.graphics.drawable.RoundedBitmapDrawableFactory;

public class Main_Activity extends AppCompatActivity {
    public TextView nameText;
    public FontIconView sex_icon;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        nameText = (TextView) findViewById(R.id.name);
        nameText.setText(login.inJson.getString("usr"));
        sex_icon = (FontIconView) findViewById(R.id.sex_icon);
        if(login.inJson.getString("gender").equals("男"))
            sex_icon.setText(getResources().getString(R.string.man_icon));
        else
            sex_icon.setText(getResources().getString(R.string.woman_icon));

        //取服务器头像内容并转为圆形
        ImageView image = (ImageView) findViewById(R.id.headImg);
        Bitmap img = base64ToBitmap(login.inJson.getString("head_img"));
        img = makeBitmapSquare(img,120);
        RoundedBitmapDrawable Img= RoundedBitmapDrawableFactory.create(getResources(),img);
        Img.setAntiAlias(true);
        Img.setCornerRadius(img.getWidth()/2);
        image.setImageDrawable(Img);

        ImageView imageCode = (ImageView) findViewById(R.id.codeImg);
        imageCode.setImageBitmap(base64ToBitmap(login.inJson.getString("code_img")));

    }
    public static Bitmap base64ToBitmap(String base64Data) {
        byte[] bytes = Base64.decode(base64Data, Base64.NO_WRAP);
        return BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
    }

    void changeName(String nameString){
        nameText.setText(nameString);
    }

    public static Bitmap makeBitmapSquare(Bitmap oldbitmap, int newWidth){
        Bitmap newbitmap=null;
        if (oldbitmap.getWidth()>oldbitmap.getHeight()){
            newbitmap=Bitmap.createBitmap(oldbitmap,oldbitmap.getWidth()/2-oldbitmap.getHeight()/2,0,oldbitmap.getHeight(),oldbitmap.getHeight());
        }else{
            newbitmap=Bitmap.createBitmap(oldbitmap,0,oldbitmap.getHeight()/2-oldbitmap.getWidth()/2,oldbitmap.getWidth(),oldbitmap.getWidth());
        }
        int width=newbitmap.getWidth();
        float scaleWidth=((float)newWidth)/width;
        Matrix matrix=new Matrix();
        matrix.postScale(scaleWidth,scaleWidth);
        newbitmap= Bitmap.createBitmap(newbitmap,0,0,width,width,matrix,true);
        return newbitmap;
    }

}
